package cn.blu10ph.trustshare.schedule;

import cn.blu10ph.trustshare.bean.node.TrustNode;
import cn.blu10ph.trustshare.constant.Constant;
import cn.blu10ph.trustshare.core.ServiceCore;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p> RemoveNotActiveNode </p >
 *
 * @author cxx
 * @date 2024/4/1 21:31
 */
@Slf4j
@Component
public class RemoveNotActiveNode {

    @Resource
    ServiceCore serviceCore;

    @Scheduled(fixedDelay = Constant.OUT_TIME, initialDelay = Constant.OUT_TIME + 30*1000L)
    public void doJob() {
        long nowTime = System.currentTimeMillis();
        Long outTime = nowTime - Constant.OUT_TIME;
        List<TrustNode> nodes = serviceCore.getAllNodeList();
        for(TrustNode node : nodes){
            // get active time
            Long activeTime = serviceCore.getNodeActive(node.getNodeId());
            if (ObjectUtils.isEmpty(activeTime) || outTime.compareTo(activeTime)>0) {
                // remove long time node
                serviceCore.removeNode(node.getNodeId());
            }
        }
    }

}
